package com.gugee.tiktok.data.consumer.blogger.core.ai;

import com.gugee.tiktok.common.model.ai.blogger.FaceRecognition;
import com.xiguaji.boot.retry.RetryableException;
import com.xiguaji.boot.toolkit.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class BloggerAiClient {
    @Autowired
    RestTemplate restTemplate;

    @Value("${xiguaji.ai.host}")
    String host;

    /**
     * 人脸识别接口
     * @param uid 博主id
     * @param picUrl 图片url
     * @return
     */
    @Retryable(value = RetryableException.class, maxAttempts = 1)
    public FaceRecognition getFaceRecognitionByPicUrl(Long uid, String picUrl) {
        String uri = host + "/facedetact";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        Map<String,Map<String,Object>> map = new HashMap<>();
        Map<String,Object> uidToUrl = new HashMap<>();
        uidToUrl.put("uid",uid);
        uidToUrl.put("url",picUrl);
        map.put("uidtourl",uidToUrl);
        HttpEntity<String> request = new HttpEntity<>(JsonUtil.parseJson(map),headers);

        ResponseEntity<FaceRecognition> responseEntity = restTemplate.postForEntity(uri,request,FaceRecognition.class);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException(String.format("get blogger error. status: %s . msg: %s", responseEntity.getStatusCodeValue(), responseEntity.getBody()));
        }
        if (responseEntity.getBody() == null) {
            throw new RetryableException("get FaceRecognition error, retry times 1. uid:" + uid + " , url:" + picUrl);
        }
        return responseEntity.getBody();
    }
}
